package com.doordu.soa.service.data.controller.aop;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.doordu.soa.service.web.service.DataValidService;
import com.doordu.soa.service.web.utils.BaseController;
import com.doordu.soa.service.web.utils.PageParam;

/**
 * 控制层的参数请求校验 Created by xiaoqun.yi on 2017/5/16.
 */
@Aspect
@Component
public class ReqValidAop {
	private static final Logger logger = LoggerFactory.getLogger(ReqValidAop.class);

//	@Value("${limit.request.count}")
//	private Integer limitRequestCount;
//	@Value("${limit.time.second}")
//	private Integer limitTimeSecond;

//	@Autowired
//	private RedisDoorduTemplate redis;
	


	@Pointcut(value = "execution(public * com.doordu.soa.service.data.controller.*.*(..)) && @annotation(io.swagger.annotations.ApiOperation)")
	public void dataController() {
	}

	

	//@Around(value = "deviceController() || userController()|| houseController() || flowController() || parkingController() || thirdController()")
	@Around(value = "dataController()")
	public Object doValid(ProceedingJoinPoint joinPoint) throws Throwable {
//		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//		HttpServletRequest request = attributes.getRequest();
//		HttpServletResponse response = attributes.getResponse();

//		Signature signature = joinPoint.getSignature();
//		MethodSignature methodSignature = (MethodSignature) signature;
//		Method targetMethod = methodSignature.getMethod();
//		if (null != targetMethod.getAnnotation(LimitRequest.class)) {
//			String ip = request.getRemoteAddr();
//			String uri = request.getRequestURI().toString();
//			String redisKey = "limit-ip-request:" + uri + ":" + ip;
//			Long maxAccessCountSec = redis.get("MAX_ACCESS_COUNT_SEC_METHOD");
//			if (maxAccessCountSec == null) {
//				maxAccessCountSec = 30L;
//			}
//			// 设置在redis中的缓存，累加1
//			long count = redis.incr(redisKey);
//			// 如果该key不存在，则从0开始计算，并且当count为1的时候，设置过期时间
//			if (count == 1) {
//				redis.expire(redisKey, limitTimeSecond);
//			}
//			// 如果redis中的count大于限制的次数，则报错
//			if (count > limitRequestCount) {
//			  logger.error("判断为机器请求接口{},大于{}次", redisKey, maxAccessCountSec);
//              Thread.sleep(3000);

//              redis.set(redisKey, 1, (long)limitTimeSecond);
//              redis.set(redisKey, 1, limitTimeSecond);
////              response.getWriter().print("The machine is tired, don't use the machine down another machine");
////              response.getWriter().flush();
////              return false;
//			}
//		}
		for (Object args : joinPoint.getArgs()) {
			String errMsg = DataValidService.checkData(args);
			if (StringUtils.isNotBlank(errMsg)) {
				return ((BaseController) joinPoint.getThis()).checkParamError(errMsg);
			}

			if (args instanceof PageParam) {
				PageParam pageParam = (PageParam) args;
				if (Integer.valueOf(pageParam.getPage()) <= 0 || Integer.valueOf(pageParam.getLimit()) <= 0) {
					return ((BaseController) joinPoint.getThis()).checkParamError("分页参数校验失败，正确格式为正整数");
				}
			}
		}
		return joinPoint.proceed(joinPoint.getArgs());
	}
}
